Files with Temporary URLs in Laravel Storage

Generating temporary URLs for files in Laravel's storage allows you to share files securely without exposing them indefinitely. This is especially useful for private files where access needs to be controlled.


Example 1: Generate a Temporary URL for a File

1. Store a File: First, ensure you have a file stored in your storage. For example, let's assume you've uploaded a file named document.pdf to the public disk.

use Illuminate\Support\Facades\Storage;

Storage::disk('public')->put('documents/document.pdf', 'File content here');

2. Generate a Temporary URL: To generate a temporary URL that is valid for a limited time (e.g., 60 minutes), use the temporaryUrl method.

$url = Storage::disk('public')->temporaryUrl('documents/document.pdf', now()->addMinutes(60));
echo $url; // Outputs a temporary URL valid for 60 minutes

Example 2: Generating Temporary URLs for Files in Private Storage

If you're using a private disk (e.g., S3), you can still generate temporary URLs.

1. Store a File in Private Disk:

Storage::disk('s3')->put('private/documents/document.pdf', 'File content here');

2. Generate Temporary URL:

$url = Storage::disk('s3')->temporaryUrl('private/documents/document.pdf', now()->addMinutes(15));
echo $url; // Outputs a temporary URL for S3

You Might Also Like

Custom Blade Directives in Laravel

# Step 1: Create a Custom Blade Directive Add custom directives in the boot method of a service prov...

Pass Arguments and Options to Artisan Commands

Enhance command flexibility by passing arguments and options to Artisan commands. This allows dynami...